<?php

namespace App\Http\Controllers\Api\Backend;

use App\Models\User;
use App\Utils\FundType;
use App\Models\UserFund;
use Illuminate\Http\Request;
use App\Utils\TransferStatus;
use App\Models\AmountTransfer;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class AmountTransferController extends Controller
{
    const CANCEL = -1;
    const DOING = 0;
    const SUCCESS = 2;

    public function index(Request $request)
    {
        $limit = $request->limit;
        $title = $request->title;
        $orderBy = $request->orderBy ? 'asc' : 'desc';
        $transfers = AmountTransfer::with(['fromUser:id,username,nickname', 'toUser:id,username,nickname'])->when($title, function ($query) use ($title) {
            return $query->where('title', 'like', '%' . $title . '%');
        })->orderBy('id', $orderBy)->paginate($limit);
        return success($transfers);
    }

    public function update(Request $request, $id)
    {
        $data = $request->all();
        if (AmountTransfer::where('id', $id)->update($data)) {
            return success();
        }
        return error();
    }

    public function destroy($id)
    {
        if (AmountTransfer::where('id', $id)->delete()) {
            return success();
        }
        return error();
    }

    public function cancel($id)
    {
        $transfer = AmountTransfer::lockForUpdate()->find($id);
        if($transfer->status == TransferStatus::CANCEL || $transfer->status == TransferStatus::FINISH) {
            return error('订单已取消或已完成');
        }
        DB::beginTransaction();
        try {
            $user = User::find($transfer->from_user_id);
            $priceTotal = $transfer->price + $transfer->handle_fee;
            $user->increment('amount', $priceTotal);
            UserFund::create([
                'user_id' => $user->id,
                'type' => FundType::TRANSFER,
                'change_amount' => $priceTotal,
                'after_amount' => $user->amount,
                'content' => '转让订单取消,' . $transfer->price . '元，手续费' . $transfer->handle_fee . '元',
                'remark' => '转让订单'
            ]);
            $transfer->status = TransferStatus::CANCEL;
            $transfer->save();
            DB::commit();
            return success();
        }catch(\Exception $e) {
            DB::rollback();
        }
        return error();
    }

    public function confirm($id)
    {
        DB::beginTransaction();
        try {
            $transfer =  AmountTransfer::lockForUpdate()->find($id);
            if ($transfer->status == TransferStatus::CANCEL || $transfer->status == TransferStatus::FINISH) {
                return error('订单已取消或已完成');
            }
            // if (!$transfer->image) {
            //     return errorMsg('上传凭证为空，不能确认');
            // }
            $fromUser = User::find($transfer->from_user_id);
            UserFund::create([
                'user_id' => $fromUser->id,
                'type' => FundType::TRANSFER,
                'change_amount' => 0,
                'after_amount' => $fromUser->amount,
                'content' => '完成转让交易',
                'remark' => '转让订单'
            ]);
            $toUser = User::find($transfer->to_user_id);
            $toUser->increment('amount', $transfer->price);
            UserFund::create([
                'user_id' => $toUser->id,
                'type' => FundType::TRANSFER,
                'change_amount' => $transfer->price,
                'after_amount' => $toUser->amount,
                'content' => '完成转让交易,获得余额' . $transfer->price . '元',
                'remark' => '转让订单'
            ]);
            $transfer->status = TransferStatus::FINISH;
            $transfer->save();
            DB::commit();
            return success($transfer);
        } catch (\Exception $e) {
            DB::rollback();
            return error($e->getMessage());
        }
    }
}
